package com.lollipop.programming.thread.sequential;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;

/**
 * @Author Lollipop
 * @Version 1.0
 * @Date 2025/4/14 9:19
 * @Description 有 T1、T2、T3 三个线程，怎么保证 T2 在 T1 执行完后执行，T3 在 T2 执行完后执行 - 使用CountDownLatch
 */
@Slf4j
public class ThreadCountDownLatch {
    public static void main(String[] args) {
        // 创建CountDownLatch对象，初始值为1
        CountDownLatch latch1 = new CountDownLatch(1);
        CountDownLatch latch2 = new CountDownLatch(1);

        Thread t1 = new Thread(() -> {
            // T1执行
            log.info("T1执行");
            // 计数器减1
            latch1.countDown();
        });

        Thread t2 = new Thread(() -> {
            try {
                // 等待T1执行完
                latch1.await();
                // T2执行
                log.info("T2执行");
                // 计数器减1
                latch2.countDown();
            } catch (InterruptedException e) {
                log.error("T2执行异常：{}", e.getMessage());
            }
        });

        Thread t3 = new Thread(() -> {
            try {
                // 等待T2执行完
                latch2.await();
                // T3执行
                log.info("T3执行");
            } catch (InterruptedException e) {
                log.info("T3执行异常：{}", e.getMessage());
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
